<template>
  <SkeletonLoader v-if="!productData || !productData.id" :type="'product-card'"></SkeletonLoader>
  <!-- 商品详情顶部内容容器 -->
  <div class="detail-top-content" v-else>
    <!-- 左侧图片区域 -->
    <section class="go-flex left-image">
      <!-- 缩略图导航区域 -->
      <div class="thumbnail-nav">
        <!-- 向上滚动按钮 -->
        <button class="nav-arrow up" @click="prevThumbnail" :disabled="currentImageIndex === 0">
          <span class="arrow">
            <UpOutlined />
          </span>
        </button>
        <!-- 缩略图列表 -->
        <div class="thumbnail-list">
          <div v-for="(image, index) in productData?.detail_images" :key="index" class="thumbnail"
            :class="{ active: currentImageIndex === index }" @click="selectImage(index)">
            <img :src="image" :alt="`${productData.name} - view ${index + 1}`" />
          </div>
        </div>
        <!-- 向下滚动按钮 -->
        <button class="nav-arrow down" @click="nextThumbnail"
          :disabled="currentImageIndex === productData?.detail_images.length - 1">
          <span class="arrow">
            <DownOutlined />
          </span>
        </button>
      </div>

      <!-- 商品主图展示区域 -->
      <div class="product-gallery">
        <!-- 上一张图片按钮 -->
        <button class="gallery-nav prev" @click="prevImage" v-if="currentImageIndex > 0">
          <span class="arrow">&#x2039;</span>
        </button>
        <!-- 主图显示区域 -->
        <div class="main-image">
          <img :src="currentImage" :alt="productData.name" />
        </div>
        <!-- 下一张图片按钮 -->
        <button class="gallery-nav next" @click="nextImage"
          v-if="productData?.detail_images && currentImageIndex < productData?.detail_images.length - 1">
          <span class="arrow">&#x203A;</span>
        </button>
      </div>
    </section>

    <!-- 商品信息区域 -->
    <section class="product-info">
      <!-- 商品标题和价格 -->
      <div class="product-header">
        <!-- <h1 class="brand-name">Duonin</h1> -->
        <h2 class="product-name">{{ productData.name }}</h2>
        <!-- 使用ProductRating组件替换原来的五星评价部分 -->
        <ProductRating :comments="comments" />
        <div class="product-price go-flex-sc">
          <div class="price">
            {{ useCurrency.currentCurrency.unit }} {{ globalProperties?.$ConvertPrice(productData.min_price) }}
            <span class="underline-sty">{{ useCurrency.currentCurrency.unit }} {{
              globalProperties?.$ConvertPrice(productData.max_origin_price) }}</span>
            <!-- 折扣标签 -->
            <span v-if="productData.discount_enabled == 1" class="discount-label">
              {{ '-' + productData.discount }}%
            </span>
            <span class="earn">Earn {{ points }} Points</span>
          </div>
          <div class="product-price-num">
            <img :src="SVG_ICONS.visit" /><span v-show="visitCount">{{ visitCount }}</span>
          </div>
        </div>
      </div>

      <!-- 商品选项区域 -->
      <div class="product-options">
        <!-- 颜色选择 -->
        <div class="option-group" v-if="productData.spec_list.length > 0">
          <div class="option-label">
            COLOUR: {{ colorNameActive }}
          </div>
          <div class="color-options">
            <template v-for="item in productData.spec_list" :key="item.name">
              <button v-if="item.name.toLowerCase() === 'color'" class="color-option">
                <span v-for="(color, index) in item.value" :key="index" class="color-swatch"
                  :class="{ active: colorActive === color.name }" @click="colorClick(color.name)">
                  <img :src="color.name" alt="">
                </span>
              </button>
            </template>
          </div>
        </div>

        <!-- 尺码选择 -->
        <div class="option-group" v-if="filteredSizes.length > 0">
          <div class="option-label size-header">
            <div>
              <span class="option-label">SIZE:</span>
              <!-- <div class="size-region-dropdown">
                <button class="region-button" @click="toggleRegionDropdown">
                  {{ currentRegion }} SIZE <span class="dropdown-arrow"
                    :class="{ 'arrow-up': showRegionDropdown }">▼</span>
                </button>
                <div class="region-menu" v-if="showRegionDropdown">
                  <div v-for="region in regions" :key="region" class="region-option"
                    :class="{ 'active': currentRegion === region }" @click="selectRegion(region)">
                    {{ region }}
                  </div>
                </div>
              </div> -->
            </div>
            <a class="size-guide" @click="showSizeGuide">
              <svg class="icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="25"
                height="16" viewBox="0 0 25 16">
                <image width="25" height="16"
                  xlink:href="data:img/png;base64,iVBORw0KGgoAAAANSUhEUgAAABkAAAAQCAYAAADj5tSrAAAAWElEQVQ4jWNUVlaexsDAkMlAOzCdCdmCO3fuMFCbDTKfiYY+gINRS6hjiYqKClY2qWrwWkJNAMon/2ltyWjqGsSWMDIy0t6S//9pl8hAlkynmekgwMAwHQD5bhxCu6stFwAAAABJRU5ErkJggg==">
                </image>
              </svg>SIZE GUIDE
            </a>
          </div>
          <div class="size-options">
            <button v-for="size in filteredSizes" :key="size.name" class="size-button"
              :class="{ 'active': sizeActive === size.name, 'out-of-stock': !size.inStock }"
              @click="sizeClick(size.name)" :disabled="!size.inStock">
              {{ size.name }}
            </button>
          </div>
        </div>

        <!-- 数量 -->
        <div class="option-group quantity-selector">
          <div class="option-label" style="padding-top:0;">QUANTITY:</div>
          <div class="quantity-controls">
            <button class="quantity-button" @click="decrementQuantity" :disabled="quantity <= 1">-</button>
            <span class="quantity-display">{{ quantity }}</span>
            <button class="quantity-button" @click="incrementQuantity">+</button>
          </div>
        </div>
      </div>

      <!-- 添加到购物袋和收藏按钮 -->
      <div class="product-actions">
        <div class="action-buttons">
          <!-- 添加到购物袋按钮 -->
          <button class="add-to-bag" @click="buyFn">
            ADD TO BAG
          </button>
          <!-- 收藏按钮 -->
          <button class="wishlist-button" v-if="!productData.favorite" @click="collectFn(false)">
            <img :src="SVG_ICONS.favourite_default" alt="Add to Wishlist" />
          </button>
          <button class="wishlist-button" v-else @click="collectFn(true)">
            <img :src="SVG_ICONS.favourite_active" alt="Remove from Wishlist" />
          </button>
        </div>
      </div>

      <!-- 配送信息 -->
      <!-- TODO 还未对接 -->
      <div class="delivery-info">
        <!-- <div class="delivery-icon">
          <img
            src="https://www.reiss.com/static-content/ux-fabric/iconography-graphics/feature/reiss/deliveryreturns-xl-default.svg"
            alt="Delivery" />
        </div> -->
        <div class="delivery-text">
          <p>WE OFFER FREE NEXT-DAY DELIVERY AND RETURN SERVICES. OTHER DELIVERY AND RETURN OPTIONS AND COSTS <a
              href="#" @click="toTerms" class="terms-link">CLICK HERE</a></p>
        </div>
      </div>

      <!-- 商品描述 -->
      <div class="product-description">
        <p :class="{ 'truncated': !showFullDescription }">{{ productData.description }}</p>
        <button v-if="isDescriptionLong" class="read-more" @click="toggleDescription">
          {{ showFullDescription ? 'SHOW LESS' : 'READ MORE' }}
        </button>
      </div>

      <!-- 商品编号 -->
      <!-- <div class="product-code">
        <span>PRODUCT CODE:</span>Duonin-{{ productData.id }}
      </div> -->

      <!-- 商品详情和保养信息 -->
      <div class="product-details" v-for="(item, index) in productData.goods_service" :key="index">
        <button class="details-button" @click="toggleCareInfo(index)">
          <span>{{ item.name }}</span>
          <span class="dropdown-arrow" :class="{ 'arrow-up': showCareInfo[index] }">
            <DownOutlined :style="{ fontSize: '10px' }" />
          </span>
        </button>
        <div class="care-info" v-show="showCareInfo[index]">
          <p>{{ item.content }}</p>
        </div>
      </div>
      <!-- 退货相关 -->
      <ServiceBenefits />
    </section>
  </div>
  <a-drawer title="Size Guide" :placement="placement" :closable="true" :visible="sizeVisible" :width="480"
    @close="onClose">
    <SizeTable.default :sizeData="productData"></SizeTable.default>
  </a-drawer>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, nextTick, getCurrentInstance, type ComponentInternalInstance } from 'vue';
// @ts-ignore
import * as SizeTable from '@/views/GoodDetails/components/sizeTable.vue';
import SkeletonLoader from '@/views/GoodDetails/components/SkeletonLoader.vue';
import { UpOutlined, DownOutlined } from '@ant-design/icons-vue';
// @ts-ignore
import SVG_ICONS from '@/assets/SVG_ICONS';
// @ts-ignore
import ServiceBenefits from '@/views/GoodDetails/components/ServiceBenefits.vue';
// @ts-ignore
import { getGoodDetails } from '@/api/goods';
// @ts-ignore
import { useGlobalStore } from '@/store';
// @ts-ignore
import { addVisit, addFavorite, deleteFavorite, getDetail, addCarts } from "@/api/goods";
// @ts-ignore
import { useCurrencyStore } from '@/store'
import { useRoute } from 'vue-router';
// @ts-ignore
import { useCartStore } from '@/store/cart';
import { message } from 'ant-design-vue';
import mitt from '@/utils/mitt';
// 引入ProductRating组件
import ProductRating from '@/components/ProductRating.vue';
import { getToken } from '@/utils/auth';
import { useRouter } from 'vue-router';
import { getFavoriteList } from "@/api/goods";
import { Session } from '@/utils/storage';

const router = useRouter();

const points = computed(() => {
  return Math.round(productData.value.min_price / 10);
});

// 评分摘要显示状态
const showRatingSummary = ref(false);

// 评分数据
const ratingData = ref<Array<{ stars: number, count: number, percentage: number }>>([]);

// 评分数据初始化
const initRatingData = () => {
  // 清空现有数据
  ratingData.value = [];

  // 初始化评分计数
  const starCounts = [0, 0, 0, 0, 0]; // 索引0对应1星，索引4对应5星

  // 统计各星级评价数量
  comments.value.forEach((item: any) => {
    const score = Math.min(Math.max(Math.floor(item.score), 1), 5); // 确保分数在1-5之间
    starCounts[score - 1]++; // 对应星级计数加1
  });

  // 计算总评价数
  const total = comments.value.length;

  // 生成评分数据，从5星到1星排序
  for (let i = 5; i >= 1; i--) {
    const count = starCounts[i - 1];
    const percentage = total > 0 ? Math.round((count / total) * 100) : 0;

    ratingData.value.push({
      stars: i,
      count: count,
      percentage: percentage
    });
  }
};

// 尺码地区选择
const regions = ['US', 'AU', 'UK', 'CN', 'JP', 'EU'] as const;
type RegionType = typeof regions[number];
const currentRegion = ref<RegionType>('US');
const showRegionDropdown = ref(false);

const sizeVisible = ref(false)
const cartStore = useCartStore()
const placement = ref('right')
const onClose = () => {
  sizeVisible.value = false
}

// 更新收藏状态
const updateTabsListFavorites = () => {
  try {
    // @ts-ignore
    const collectedItems = cartStore.getCollect();
    if (!collectedItems || !collectedItems.length) return;
    // @ts-ignore
    const isFavorited = collectedItems.some(collection => collection.goods_id === productData.value.id);
    if (isFavorited) {
      productData.value.favorite = true;
    } else {
      productData.value.favorite = false;
    }
  } catch (error) {
    console.error('更新商品收藏状态失败:', error);
  }
}

// 根据当前选择的地区过滤尺码
const filteredSizes = computed(() => {
  // 从商品规格中获取尺码
  const sizeSpec = productData.value?.spec_list?.find(spec => spec.name.toLowerCase() === 'size');
  if (!sizeSpec || !sizeSpec.value) {
    return [];
  }

  // 返回尺码列表，并根据是否有库存设置状态
  return sizeSpec.value.map(size => {
    // 计算该尺码是否有可用的SKU（与当前选中的颜色匹配）
    let inStock = true;
    if (colorActive.value) {
      // 检查是否存在该颜色+尺码的组合
      inStock = productData.value.sku_list.some(sku => {
        const skuColorSpec = sku.spec_parsed.find(s => s.name.toLowerCase() === 'color');
        const skuSizeSpec = sku.spec_parsed.find(s => s.name.toLowerCase() === 'size');
        return skuColorSpec?.value === colorActive.value && skuSizeSpec?.value === size.name;
      });
    }

    return {
      name: size.name,
      inStock: inStock
    };
  });
});

// 切换地区下拉框
const toggleRegionDropdown = () => {
  showRegionDropdown.value = !showRegionDropdown.value;
};

// 选择地区
const selectRegion = (region: RegionType) => {
  currentRegion.value = region;
  showRegionDropdown.value = false;
};

// 总评价数
const totalReviews = computed(() => {
  return ratingData.value.reduce((total, item) => total + item.count, 0);
});

// 平均评分
const averageRating = computed(() => {
  const sum = ratingData.value.reduce((total, item) => total + (item.stars * item.count), 0);
  return totalReviews.value > 0 ? (sum / totalReviews.value).toFixed(1) : '0.0';
});

interface GoodsService {
  name: string;
  content: string;
}

/**
 * 规格值接口定义
 */
interface SpecValue {
  name: string;
  value?: string;
  code?: string;
}

/**
 * SKU项接口定义
 */
interface SkuItem {
  id: number;
  goods_id: number;
  spec_parsed: SpecValue[];
  spec: SpecValue[];
  image: string;
  price: string;
  origin_price: string;
  stock: number;
  goods_name: string;
}

interface ProductData {
  id: number;
  name: string;
  price: number;
  description: string;
  spec_list: {
    name: string;
    value: { name: string; code?: string }[];
  }[];
  sku_list: SkuItem[];
  detail_images: string[];
  code?: string;
  care_instructions?: string;
  favorite?: boolean;
  goods_service?: GoodsService[];
}

const useCurrency = useCurrencyStore()

// 获取组件实例
const instance = getCurrentInstance();
// 获取全局属性和转换价格方法
const globalProperties = instance ? (instance as any).proxy : null;

const props = defineProps<{
  goodId: string;
}>();


const detailData = ref<ProductData>({
  id: 0,
  name: '',
  price: 0,
  description: '',
  spec_list: [],
  detail_images: [],
  favorite: false,
  goods_service: [
    {
      name: '',
      content: ''
    }
  ]
})
const comments = ref<any[]>([]);
//获取商品详情
const getDetailData = () => {
  getDetail(props.goodId).then(res => {
    console.log(res);
    if (res.code === 200) {
      detailData.value = res.result.goods_detail;
      comments.value = res.result.goods_comments;
      // 刷新最近浏览
      refreshVisit();
    }
  });
}


/**
 * 默认商品数据
 * 用于初始化商品数据状态
 */
const defaultProduct: ProductData = {
  id: 0,
  name: '',
  price: 0,
  description: '',
  spec_list: [],
  sku_list: [],
  detail_images: [
    // 'https://cdn.platform.next/common/items/default/default/itemimages/3_4Ratio/product/lge/AV5079s.jpg?im=Resize,width=750',
    // 'https://cdn.platform.next/common/items/default/default/itemimages/3_4Ratio/product/lge/AV5079s3.jpg?im=Resize,width=480',
    // 'https://cdn.platform.next/common/items/default/default/itemimages/3_4Ratio/product/lge/AV5079s4.jpg?im=Resize,width=480',
    // 'https://cdn.platform.next/common/items/default/default/itemimages/3_4Ratio/product/lge/AV5079s2.jpg?im=Resize,width=480'
  ],
};

// 状态管理
/**
 * 商品数据响应式引用
 */
const productData = ref<ProductData>({ ...defaultProduct });

/**
 * 当前显示的图片索引
 */
const currentImageIndex = ref(0);

/**
 * 当前选中的颜色
 */
const colorActive = ref('');

/**
 * 当前选中的尺码
 */
const sizeActive = ref('');

// 当前选中的规格对应的SKU
const selectedSku = ref<any>(null);

// 当前商品图片
const currentProductImage = ref('');

/**
 * 是否显示保养信息
 */
const showCareInfo = ref<boolean[]>([]);

/**
 * 是否显示完整描述
 */
const showFullDescription = ref(false);

/**
 * 检查描述是否超过3行
 */
const isDescriptionLong = ref(false);

// 计算属性
/**
 * 当前显示的图片URL
 * 根据currentImageIndex计算当前应该显示的图片
 */
const currentImage = computed(() => {
  return productData.value.detail_images[currentImageIndex.value];
});

/**
 * 根据已选择的规格获取对应的SKU
 */
const getSelectedSku = () => {
  if (!colorActive.value || !sizeActive.value || !productData.value?.sku_list) {
    console.log('未满足查询条件:', {
      color: colorActive.value,
      size: sizeActive.value,
      hasList: !!productData.value?.sku_list
    });
    return null;
  }

  // 检查SKU列表中的每一项
  for (const sku of productData.value.sku_list) {
    // 找到颜色规格和尺码规格
    const colorSpec = sku.spec_parsed.find(s => s.name.toLowerCase() === 'color');
    const sizeSpec = sku.spec_parsed.find(s => s.name.toLowerCase() === 'size');

    // 检查是否匹配当前选中的颜色和尺码
    if (colorSpec && sizeSpec) {
      if (colorSpec.value === colorActive.value && sizeSpec.value === sizeActive.value) {
        console.log('找到匹配SKU:', sku.id, '颜色:', colorSpec.value, '尺码:', sizeSpec.value);
        return sku;
      }
    }
  }

  console.log('未找到匹配SKU, 当前选择 - 颜色:', colorActive.value, '尺码:', sizeActive.value);
  return null;
};
let colorNameActive = ref('')
/**
 * 更新选中的SKU和相关信息
 */
const updateSelectedSku = () => {
  const sku = getSelectedSku();
  if (sku) {
    console.log('更新选中SKU:', sku.id);
    selectedSku.value = sku;
    currentProductImage.value = sku.image;
    colorNameActive.value = sku.color_name
  } else {
    console.log('未找到匹配的SKU组合');
    selectedSku.value = null;
  }
};

watch(() => detailData.value, (newVal) => {
  if (!newVal) return;
  
  productData.value = { ...newVal };
  console.log('商品数据已更新:', productData.value);

  // 如果有规格数据和SKU数据
  if (productData.value?.sku_list?.length > 0) {
    // 使用第一个SKU的规格作为默认值
    const firstSku = productData.value.sku_list[0];
    colorNameActive.value = firstSku.color_name

    // 查找颜色和尺码规格
    const colorSpec = firstSku.spec_parsed.find(spec => spec.name.toLowerCase() === 'color');
    const sizeSpec = firstSku.spec_parsed.find(spec => spec.name.toLowerCase() === 'size');

    // 设置初始值
    if (colorSpec && colorSpec.value) {
      colorActive.value = colorSpec.value;
      console.log('初始颜色设置为:', colorActive.value);
    }

    if (sizeSpec && sizeSpec.value) {
      sizeActive.value = sizeSpec.value;
      console.log('初始尺码设置为:', sizeActive.value);
    }

    // 设置初始选中的SKU
    selectedSku.value = firstSku;
    console.log('初始SKU设置为:', firstSku.id);
  }

  updateTabsListFavorites();
});

// 监听颜色和尺码变化，更新选中的SKU
watch([colorActive, sizeActive], () => {
  console.log('规格选择已更新 - 颜色:', colorActive.value, '尺码:', sizeActive.value);
  updateSelectedSku();
});

onMounted(() => {
  checkDescriptionLength();
  initRatingData();
  // updateTabsListFavorites();
  getDetailData();
})

const visitCount = ref(null)
// 刷新最近浏览
const refreshVisit = () => {
  addVisit({ id: detailData.value.id }).then((res: any) => {
    if (res.code == 200) {
      visitCount.value = res.result.visit
    }
  })

}


const toTerms = () => {
  // 重新打开一个页签到terms页面
  window.open('/terms', '_blank');
};

// 方法定义
/**
 * 显示上一张图片
 * 如果当前不是第一张图片，则索引减1
 */
const prevImage = () => {
  if (currentImageIndex.value > 0) {
    currentImageIndex.value--;
  }
};

/**
 * 显示下一张图片
 * 如果当前不是最后一张图片，则索引加1
 */
const nextImage = () => {
  if (productData.value.detail_images && currentImageIndex.value < productData.value.detail_images.length - 1) {
    currentImageIndex.value++;
  }
};

/**
 * 选择指定索引的图片
 * @param {number} index - 要选择的图片索引
 */
const selectImage = (index: number) => {
  currentImageIndex.value = index;
};

/**
 * 选择颜色
 * @param {string} color - 要选择的颜色URL
 */
const colorClick = (color: string) => {
  console.log('选择颜色:', color);
  colorActive.value = color;
  // 颜色变化后，重新匹配SKU
  updateSelectedSku();
};

/**
 * 选择尺码
 * @param {string} size - 要选择的尺码
 */
const sizeClick = (size: string) => {
  console.log('选择尺码:', size);
  sizeActive.value = size;
  // 尺码变化后，重新匹配SKU
  updateSelectedSku();
};

/**
 * 切换保养信息的显示状态
 */
const toggleCareInfo = (index: number) => {
  if (!showCareInfo.value[index]) {
    showCareInfo.value[index] = true;
  } else {
    showCareInfo.value[index] = false;
  }
};

/**
 * 切换商品描述的显示状态
 */
const toggleDescription = () => {
  showFullDescription.value = !showFullDescription.value;
};

/**
 * 显示尺码指南
 * 可以在这里实现尺码指南弹窗
 */
const showSizeGuide = () => {
  // 实现尺码指南弹窗
  sizeVisible.value = true
};
const isLogin = ref(!!getToken());
/**
 * 添加到购物袋
 * 检查是否已选择尺码和颜色，然后触发buy事件
 */
const buyFn = async () => {
  if(!isLogin.value) {
    message.warn('Please log in first.');
    setTimeout(() => {
      router.push('/login');
    }, 1500);
    return;
  }
  if (!sizeActive.value && filteredSizes.value.length > 0) {
    message.warn('PLEASE SELECT A SIZE');
    return;
  }
  if (!colorActive.value && productData.value.spec_list.length > 0) {
    message.warn('PLEASE SELECT A COLOR');
    return;
  }

  if (!selectedSku.value.id) {
    message.warn('SELECTED COMBINATION IS NOT AVAILABLE');
    return;
  }

  // 找到选中的SKU完整信息
  // const selectedSku = productData.value.sku_list?.find(sku => sku.id === selectedSkuId.value);
  // if (!selectedSku.value) {
  //   alert('Selected SKU not found');
  //   return;
  // }

  await addCarts({
    sku_id: selectedSku.value.id,
    num: 1,
  }).then((res: any) => {
    if (res.code === 200) {
      message.success('Add to cart success');
      mitt.emit('addShoppingCart', selectedSku.value);
    } else {
      message.success('Add to cart failed');
    }
  })

  emit('buy', {
    skuId: selectedSku.value.id,
    selectedSize: sizeActive.value,
    selectedColor: colorActive.value,
    price: selectedSku.price,
    image: selectedSku.image,
    goods_name: selectedSku.goods_name
  });
};

/**
 * 收藏商品
 * 触发collect事件
 */
const collectFn = async (isFavorite: boolean) => {
  if(!isLogin.value) {
    message.error('Please log in first.');
    setTimeout(() => {
      router.push('/login');
    }, 1500);
    return;
  }
  try {
    const res = isFavorite
      ? await deleteFavorite(String(productData.value.id))
      : await addFavorite(String(productData.value.id));

    if (res.code === 200) {
      productData.value.favorite = !isFavorite;
    }

    const favoriteResDel = await getFavoriteList()
    if (favoriteResDel.code === 200) {
      Session.set('collectList', favoriteResDel.result.data)
    }
    updateTabsListFavorites()
  } catch (error) {
    console.error('Failed to update favorite status:', error);
  }
};


/**
 * 缩略图向上滚动
 * 如果当前不是第一张图片，则索引减1
 */
const prevThumbnail = () => {
  if (currentImageIndex.value > 0) {
    currentImageIndex.value--;
  }
};

/**
 * 缩略图向下滚动
 * 如果当前不是最后一张图片，则索引加1
 */
const nextThumbnail = () => {
  if (productData.value.detail_images && currentImageIndex.value < productData.value.detail_images.length - 1) {
    currentImageIndex.value++;
  }
};

/**
 * 检查文本是否超过3行
 */
const checkDescriptionLength = () => {
  nextTick(() => {
    const descriptionElement = document.querySelector('.product-description p');
    if (descriptionElement) {
      const lineHeight = parseInt(getComputedStyle(descriptionElement).lineHeight);
      const height = descriptionElement.clientHeight;
      isDescriptionLong.value = height > lineHeight * 3;
    }
  });
};

// 监听描述内容变化
watch(() => productData.value.description, () => {
  nextTick(() => {
    checkDescriptionLength();
  });
});

// Emits 定义
/**
 * 组件事件定义
 * @property {Function} buy - 购买事件，传递商品数据和选择的尺码、颜色
 * @property {Function} collect - 收藏事件，传递商品数据
 */
const emit = defineEmits<{
  (e: 'buy', data: {
    skuId: number;
    selectedSize: string;
    selectedColor: string;
    price: string;
    image: string;
    goods_name: string;
    quantity: number;
  }): void;
}>();

// 评分摘要显示状态
const toggleRatingSummary = () => {
  showRatingSummary.value = true;
};

// 定义数量状态
const quantity = ref(1);

// 增加数量
const incrementQuantity = () => {
  quantity.value++;
};

// 减少数量
const decrementQuantity = () => {
  if (quantity.value > 1) {
    quantity.value--;
  }
};

</script>

<style lang="scss" scoped>
/* 商品详情顶部内容容器样式 */
.detail-top-content {
  display: grid;
  grid-template-columns: 1fr;
  margin: 0 auto;

  /* 响应式布局：在中等屏幕及以上使用两列布局 */
  @media (min-width: 768px) {
    grid-template-columns: 1fr 1fr;
  }
}

/* 左侧图片区域样式 */
.left-image {
  width: 100%;
  display: flex;
  flex-direction: row;
  align-items: top;
  gap: 25px;
}

/* 商品图片展示区域样式 */
.product-gallery {
  position: relative;
  max-width: 680px;
  max-height: 900px;
  margin: 0;

  /* 主图样式 */
  .main-image {
    width: 100%;
    width: 460px;
    height: 900px;
    height: auto;
    aspect-ratio: 3 / 4;
    overflow: hidden;
    margin-bottom: 10px;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }


  /* 图片导航按钮样式 */
  .gallery-nav {
    position: absolute;
    top: 46%;
    transform: translateY(-50%);
    background: none;
    border: none;
    font-size: 24px;
    color: #000;
    cursor: pointer;
    padding: 10px;
    z-index: 2;

    &.prev {
      left: 10px;
    }

    &.next {
      right: 10px;
    }
  }
}

/* 缩略图导航样式 */
.thumbnail-nav {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-top: 0;
  width: 124px;
  max-height: 670px;
  position: relative;

  /* 导航箭头按钮样式 */
  .nav-arrow {
    width: 100%;
    height: 30px;
    background: none;
    border: none;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0;
    color: #000;
    font-size: 12px;

    &:disabled {
      opacity: 0.3;
      cursor: not-allowed;
    }

    &.up {
      margin-bottom: 5px;
    }

    &.down {
      margin-top: 5px;
    }
  }

  /* 缩略图列表样式 */
  .thumbnail-list {
    flex: 1;
    display: flex;
    overflow-y: auto;
    flex-direction: column;
    scrollbar-width: none;
    align-items: center;
    justify-content: space-between;

    /* 隐藏滚动条 */
    &::-webkit-scrollbar {
      display: none;
    }
  }

  /* 单个缩略图样式 */
  .thumbnail {
    width: 100px;
    height: 135px;
    cursor: pointer;
    opacity: 0.6;
    transition: opacity 0.3s;
    margin-bottom: 8px;
    box-sizing: border-box;

    /* 激活状态样式 */
    &.active {
      opacity: 1;
      border-bottom: 2px solid #000;
    }

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  /* 响应式布局：在小屏幕上隐藏缩略图导航 */
  @media (max-width: 1020px) {
    display: none;
  }
}

/* 商品信息区域样式 */
.product-info {
  width: 100%;
  padding: 0;
  max-width: 521px;
  margin: 0 auto;
  margin-left: 36px;

  /* 商品标题和价格样式 */
  .product-header {
    margin-bottom: 16px;

    .brand-name {
      font-size: 14px;
      font-weight: bold;
      margin: 0;
      letter-spacing: 0.5px;
    }

    .product-name {
      --color-title: #232323;
      --fontsize-text: 24px;
      --fontsize-mb-text: 18px;
      margin: 0 0 5px;
      letter-spacing: 0.5px;
    }

    .product-price {
      .price {
        font-size: 26px;
        font-weight: 700;
        display: flex;
        align-items: center;
      }
    }

    .underline-sty {
      font-size: 16px;
      color: #999;
      text-decoration: line-through;
      font-weight: normal;
      margin: 0 15px;
    }

    .earn {
      margin-left: 15px;
      font-size: 16px;
    }

    .discount-label {
      background-color: rgba(0, 0, 0, 0.8);
      color: #FFFFFF;
      padding: 5px 10px;
      font-size: 14px;
    }

    .product-price-num {
      font-size: 14px;

      img {
        width: 25px;
        height: 25px;
      }

      span {
        position: relative;
        bottom: -2px;
      }
    }
  }

  /* 商品选项样式 */
  .product-options {
    border-top: 1px solid #e5e5e5;

    /* 选项组样式 */
    .option-group {
      .option-label {
        font-size: 14px;
        padding-top: 16px;
        font-weight: bold;
        margin-bottom: 15px;
        text-transform: uppercase;
        font-weight: 600;
        color: #232323;
      }

      /* 颜色选项样式 */
      .color-options {
        .color-option {
          // width: 30px;
          // height: 30px;
          border: none;
          background: none;
          padding: 2px;
          cursor: pointer;
          display: flex;

          .color-swatch {
            display: block;
            border-radius: 50%;
            border: 2px solid #cbcbcb;
            padding: 2px;
            margin-right: 10px;

            /* 激活状态样式 */

            img {
              width: 34px;
              height: 34px;
              border-radius: 50%;
            }
          }

          .color-swatch.active {
            border: 2px solid #000;
          }
        }
      }

      /* 尺码标题样式 */
      .size-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-top: 10px;
        margin-bottom: 15px;
        flex-flow: nowrap;
      }

      .size-select-wrapper {
        display: flex;
        align-items: center;
        gap: 8px;
      }

      .size-selector-dropdown {
        position: relative;
      }

      .size-region-dropdown {
        position: relative;
        display: inline-block;
        margin-left: 8px;
        border: none;
        background-color: #f6f6f6;
        margin-right: 0;
        margin-left: 8px;
        padding: 0 10px;
        height: 24px;
        border-radius: 24px;
      }

      .region-button {
        background: transparent;
        border: none;
        font-size: 14px;
        font-weight: 400;
        padding: 0;
        cursor: pointer;
        color: #232323;
        display: flex;
        align-items: center;
      }

      .dropdown-arrow {
        margin-left: 4px;
        font-size: 10px;
        transition: transform 0.3s;
      }

      .arrow-up {
        transform: rotate(180deg);
      }

      .region-menu {
        position: absolute;
        top: 100%;
        left: 0;
        width: 120px;
        background: white;
        border: 1px solid #e5e5e5;
        z-index: 100;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      }

      .region-option {
        padding: 8px 12px;
        cursor: pointer;
        font-size: 14px;
        color: #232323;
      }

      .region-option:hover,
      .region-option.active {
        background-color: #f0f0f0;
      }

      .size-guide {
        display: flex;
        align-items: center;
        text-decoration: underline;
        cursor: pointer;
        position: relative;
        font-weight: 400;
        color: #232323;
        font-weight: 600;
        font-size: 14px;
        padding: 0 !important;
        border: none !important;
        margin: 0 !important;

        svg {
          margin-right: 8px;
          width: 18px;
          height: 12px;
        }
      }

      .size-guide-icon {
        margin-right: 4px;
        position: relative;
        top: 2px;
      }

      .new-tag {
        position: absolute;
        top: -10px;
        right: -10px;
        background-color: red;
        color: white;
        font-size: 10px;
        padding: 1px 4px;
        border-radius: 2px;
        font-weight: 400;
      }

      .size-options {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        margin: 15px 0 20px;
      }

      .size-button {
        min-width: 65px;
        height: 40px;
        border: 1px solid #e0e0e0;
        background: white;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        font-size: 14px;

        &:hover {
          border-color: #000;
        }

        &.active {
          border: 2px solid #000;
          font-weight: bold;
        }

        &.out-of-stock {
          opacity: 0.5;
          cursor: not-allowed;
          text-decoration: line-through;
        }
      }
    }
  }

  /* 商品操作按钮样式 */
  .product-actions {
    margin-bottom: 30px;

    .action-buttons {
      display: flex;
      gap: 30px;
      width: 100%;

      /* 收藏按钮样式 */
      .wishlist-button {
        width: 50px;
        height: 50px;
        border: 1px solid #e0e0e0;
        background: white;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
      }

      /* 添加到购物袋按钮样式 */
      .add-to-bag {
        flex: 1;
        background: #232323;
        color: white;
        border: none;
        height: 50px;
        line-height: 50px;
        width: 96%;
        max-width: 96%;
        font-size: 14px;
        font-weight: bold;
        letter-spacing: 0.5px;
        cursor: pointer;

        &:hover {
          background: #333;
        }
      }
    }
  }

  /* 配送信息样式 */
  .delivery-info {
    border-top: 1px solid #e0e0e0;
    padding: 20px 0;
    font-size: 14px;
    line-height: 1.6;
    display: flex;

    .delivery-icon {
      margin-right: 15px;
      display: flex;
      align-items: center;
    }

    p {
      margin: 0px;
    }

    .terms-link {
      color: #000;
      text-decoration: underline;
    }
  }

  /* 商品描述样式 */
  .product-description {
    margin-bottom: 20px;
    font-size: 14px;
    line-height: 1.6;

    p {
      margin: 0;
      transition: max-height 0.3s ease;

      &.truncated {
        display: -webkit-box;
        -webkit-line-clamp: 3;
        -webkit-box-orient: vertical;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }

    .read-more {
      background: none;
      border: none;
      color: #000;
      text-decoration: underline;
      padding: 0;
      font-size: 12px;
      cursor: pointer;
      width: 100%;
      font-weight: bold;
      text-align: right;
      margin-top: 8px;
    }
  }

  /* 商品编号样式 */
  .product-code {
    font-size: 12px;
    color: #333;
    padding-bottom: 5px;
    border-bottom: 1px solid #e0e0e0;

    span {
      color: #000;
      font-weight: bold;
      margin-right: 6px;
    }
  }

  /* 商品详情和保养信息样式 */
  .product-details {
    border-bottom: 1px solid #e0e0e0;

    .details-button {
      width: 100%;
      padding: 20px 0;
      background: none;
      border: 0;
      font-size: 16px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      cursor: pointer;

      span {
        border: none;
        color: #000;
        font-weight: bold;
      }

      .dropdown-arrow {
        font-size: 10px;
        transition: transform 0.3s;

        /* 箭头向上旋转 */
        &.arrow-up {
          transform: rotate(180deg);
        }
      }
    }
  }
}

/* 响应式布局：小屏幕样式 */
@media (max-width: 767px) {
  .detail-top-content {
    grid-template-columns: 1fr;
    padding: 0 15px;
  }

  .left-image {
    flex-direction: column;
    gap: 10px;
  }

  .product-gallery {
    width: 100%;
    max-width: 100%;

    .main-image {
      width: 100%;
      height: auto;
    }

    .gallery-nav {
      top: 50%;
    }
  }

  .thumbnail-nav {
    display: flex;
    flex-direction: row;
    width: 100%;
    max-height: 100px;
    overflow-x: auto;
    padding: 10px 0;
    gap: 10px;

    .thumbnail {
      width: 70px;
      height: 90px;
      margin-right: 8px;
      margin-bottom: 0;
    }

    .nav-arrow {
      display: none;
    }

    .thumbnail-list {
      flex-direction: row;
      overflow-x: auto;
      overflow-y: hidden;
    }
  }

  .product-info {
    max-width: 100%;
    padding: 0;
    margin-top: 20px;

    .product-header {
      .product-name {
        font-size: 20px;
      }

      .product-price {
        .price {
          font-size: 20px;
        }
      }
    }

    .size-options {
      flex-wrap: wrap;
      justify-content: flex-start;

      .size-button {
        min-width: 55px;
        height: 35px;
        font-size: 12px;
      }
    }

    .size-header {
      flex-direction: column;
      align-items: flex-start;

      .size-guide {
        margin-top: 10px;
      }
    }

    .option-group {
      margin-bottom: 11px;
    }

    .quantity-selector {
      .quantity-controls {
        width: 100%;
        max-width: 150px;
      }
    }

    .product-actions {
      .action-buttons {
        .add-to-bag {
          height: 45px;
          line-height: 45px;
          font-size: 14px;
        }

        .wishlist-button {
          width: 50px;
          height: 50px;
        }
      }
    }

    .delivery-info {
      flex-direction: column;

      .delivery-icon {
        margin-bottom: 10px;
      }
    }
  }

  .rating-summary {
    width: 100%;
    max-width: 300px;
  }
}

/* 平板电脑响应式样式 */
@media (min-width: 768px) and (max-width: 1024px) {
  .detail-top-content {
    gap: 20px;
  }

  .left-image {
    gap: 15px;
  }

  .product-gallery {
    max-width: 450px;

    .main-image {
      width: 450px;
      height: auto;
    }
  }

  .thumbnail-nav {
    width: 100px;

    .thumbnail {
      width: 80px;
      height: 110px;
    }
  }

  .product-info {
    max-width: 100%;
  }
}

/* 小型桌面响应式样式 */
@media (min-width: 1025px) and (max-width: 1280px) {
  .product-gallery {
    max-width: 550px;

    .main-image {
      width: 550px;
    }
  }

  .product-info {
    max-width: 480px;
  }
}

/* 五星好评率样式 */
.rating-section {
  // margin-bottom: 10px;
  position: relative;
}

.rating-stars {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.star-icon {
  color: #AE8877;
  font-size: 24px;
}

.gw-rv-avg-rating__star {
  color: #AE8877;
}

.review-count {
  margin-left: 8px;
  font-size: 18px;
  color: #555;
  font-weight: bold;
  // text-decoration: underline;
}

.rating-summary {
  position: absolute;
  top: 100%;
  left: 0;
  width: 320px;
  background: white;
  border: 1px solid #e5e5e5;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 15px;
  z-index: 100;
  border-radius: 4px;
}

.rating-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.rating-value {
  font-size: 18px;
  font-weight: bold;
  margin-right: 10px;
}

.rating-text {
  font-size: 13px;
  color: #555;
}

.rating-bars {
  margin-bottom: 10px;
}

.rating-bar-row {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.rating-label {
  width: 30px;
  font-size: 13px;
  color: #333;
  font-weight: bold;

  .star {
    position: relative;
    top: -1px;
    right: -1px;
  }
}

.rating-bar-container {
  flex: 1;
  height: 14px;
  background-color: #f0f0f0;
  margin: 0 10px;
  border-radius: 7px;
  overflow: hidden;
}

.rating-bar {
  height: 100%;
  background-color: #c29a8f;
  border-radius: 7px;
}

.rating-count {
  width: 25px;
  font-size: 13px;
  text-align: right;
  color: #555;
}

.rating-footer {
  text-align: center;
  margin-top: 15px;
}

.view-all-reviews {
  font-size: 13px;
  color: #000;
  text-decoration: none;
  font-weight: 500;
}

/* 移动端响应式样式 */
@media (max-width: 576px) {
  .rating-summary {
    width: 100%;
    max-width: 300px;
  }

  .rating-label {
    width: 25px;
    font-size: 12px;
  }

  .rating-count {
    width: 20px;
    font-size: 12px;
  }
}

/* 数量选择器样式 */
.quantity-selector {
  margin-top: 20px;
  margin-bottom: 20px;

  .option-label {
    font-size: 14px;
    font-weight: bold;
    margin-bottom: 15px;
    text-transform: uppercase;
    font-weight: 600;
    color: #232323;
  }

  .quantity-controls {
    display: flex;
    align-items: center;
    border: 1px solid #e0e0e0;
    width: fit-content;
    // border-radius: 4px; // 边框圆角，使其看起来更像图片中的样式
  }

  .quantity-button {
    background-color: white;
    border: none;
    color: #333;
    cursor: pointer;
    font-size: 26px;
    padding: 0px 12px; // 按钮内边距
    min-width: 40px; // 按钮最小宽度

    &:disabled {
      color: #ccc;
      cursor: not-allowed;
    }

    // &:first-child {
    //   border-left: none;
    //   border-top-left-radius: 4px;
    //   border-bottom-left-radius: 4px;
    // }

    // &:last-child {
    //   border-right: none;
    //   border-top-right-radius: 4px;
    //   border-bottom-right-radius: 4px;
    // }
  }

  .quantity-display {
    font-size: 16px;
    font-weight: 400; // 与图片中数字的粗细更接近
    padding: 0 15px; // 数字两边的内边距
    min-width: 30px; // 数字显示区域的最小宽度，避免抖动
    text-align: center;
    height: 40px;
    line-height: 40px; // 垂直居中
  }
}

/* 在"退货相关"注释处添加服务保障区域 */
.service-benefits {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 20px;
  margin: 30px 0;
  padding: 15px 0;
}

.benefit-item {
  display: flex;
  align-items: center;
  padding: 10px;
  background-color: #f9f9f9;
}

.benefit-icon {
  width: 24px;
  height: 24px;
  margin-right: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #232323;
}

.benefit-text {
  font-size: 13px;
  color: #232323;
  cursor: pointer;

  &:hover {
    text-decoration: underline;
  }
}

/* 移动端适配 */
@media (max-width: 767px) {
  .service-benefits {
    grid-template-columns: 1fr;
    grid-gap: 10px;
  }
}
</style>